//
//  SQAddressListViewController.m
//  pai
//
//  Created by pro on 14-11-17.
//  Copyright (c) 2014年 linjunjing. All rights reserved.
//

#import "SQAddressListViewController.h"
#import "SQNewAddressViewController.h"
#import "Global.h"

@interface SQAddressListViewController ()

@end

@implementation SQAddressListViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self setTitle:@"收货地址管理"];
    
    [self getAddressInfo];
}
-(void)getAddressInfo
{
    my_stuff_t stuff;
    stuff.base.msgtype = 1030;
    stuff.base.len = sizeof(stuff);
    stuff.base.error = 0;
    stuff.type = 2001;
    strcpy(stuff.username, [[Global instance].userinfo.username UTF8String]);
    
    NSMutableData* msgData = [NSMutableData data];
    [msgData appendBytes:&stuff length:sizeof(stuff)];
    
    [super sendData:msgData tag:1 withHUD:YES];
}

-(void)initlist
{
    [self.view setBackgroundColor:[UIColor colorWithRed:240/255.0 green:240/255.0 blue:240/255.0 alpha:1]];
    //添加按钮
    UIButton* addBtn = [[UIButton alloc]initWithFrame:CGRectMake(7, self.MyNavigationBar.frame.origin.y+self.MyNavigationBar.frame.size.height + 20, 305, 70)];
    [addBtn setBackgroundImage:[UIImage imageNamed:@"address_add"] forState:UIControlStateNormal];
    [addBtn addTarget:self action:@selector(addNewAddress:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:addBtn];
    
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(302, 68);
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    
    self.myCollection = [[UICollectionView alloc]initWithFrame:CGRectMake(0, addBtn.frame.origin.y+addBtn.frame.size.height+20, 320, [[UIScreen  mainScreen] bounds].size.height - 44 - addBtn.frame.origin.y-addBtn.frame.size.height -20) collectionViewLayout:flowLayout];
    self.myCollection.backgroundColor = [UIColor colorWithRed:240/255.0 green:240/255.0 blue:240/255.0 alpha:1];
    if ([self.type isEqualToString:@"edit"]) {
        [self.myCollection registerClass:[SQAddressEditCell class] forCellWithReuseIdentifier:@"SQAddressEditCell"];
    }else{
        [self.myCollection registerClass:[SQAddressSelectCell class] forCellWithReuseIdentifier:@"SQAddressSelectCell"];
    }
    [self.view addSubview:self.myCollection];
    
    //NSLog(@"dataarr length:%d",self.dataMArr.count);
    
//    self.dataMArr = [NSMutableArray array];
//    for(NSInteger index = 0;index<10; index++){
//        NSString *name = @"王小明";
//        NSString *mobile = @"13333333333";
//        NSString *address = @"浙江省杭州市滨江区XXXXX路XXXXX号XXXX楼XXXX室";
//        NSDictionary *dic = @{@"name": name, @"mobile":mobile,@"address":address};
//        [self.dataMArr addObject:dic];
//    }
    self.myCollection.delegate = self;
    self.myCollection.dataSource = self;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - Collection View Data Source
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataMArr.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    //NSLog(@"row:%d",indexPath.row);
    if ([self.type isEqualToString:@"edit"]) {
        NSLog(@"edit");
        static NSString *cellIdentifier = @"SQAddressEditCell";
        SQAddressEditCell *cell = (SQAddressEditCell *)[collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
        
        addr_t item;
        [[self.dataMArr objectAtIndex:indexPath.row]getValue:&item];
        [cell setItem:item];
        cell.delegate = nil;
        cell.delegate = self;
        return cell;
    }else{
        NSLog(@"select");
        static NSString *cellIdentifier = @"SQAddressSelectCell";
        SQAddressSelectCell *cell = (SQAddressSelectCell *)[collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
        
        addr_t item;
        [[self.dataMArr objectAtIndex:indexPath.row]getValue:&item];
        [cell setItem:item];
        if (self.selectedId == item.address_id)
        {
            [cell setCheckboxSelected:YES];
        }else{
            [cell setCheckboxSelected:NO];
        }
        return cell;
    }
    return nil;
};
//点击元素触发事件
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    
    if ([self.type isEqualToString:@"edit"]) {
        
    }else{
        //获取点击的地址
        addr_t item;
        [[self.dataMArr objectAtIndex:indexPath.row]getValue:&item];
        //设置地址
        [self setAddress:item];
    }
}
-(void)addNewAddress:(UIButton*)btn
{
    SQNewAddressViewController* navc = [[SQNewAddressViewController alloc]init];
    navc.delegate = nil;
    navc.delegate = self;
    [self.navigationController pushViewController:navc animated:YES];
}
-(void)addAddress
{
    //[self.dataMArr addObject:[NSValue value:&address withObjCType:@encode(struct addr_t)]];
    [self getAddressInfo];
    //[self.myCollection reloadData];
}
-(void)changeAddress:(addr_t)address
{
    addr_t item;
    for (NSInteger i=0; i<self.dataMArr.count; i++) {
        [[self.dataMArr objectAtIndex:i]getValue:&item];
        if (item.address_id == address.address_id) {
            [self.dataMArr setObject:[NSValue value:&address withObjCType:@encode(struct addr_t)] atIndexedSubscript:i];
        }
    }
}
-(void)setAddress:(addr_t)address
{
    [self.delegate addressSelected:address];
    [self.navigationController popViewControllerAnimated:YES];
//    self.selectedId = address.address_id;
//    [self.myCollection reloadData];
}
-(void)addressdelete:(NSInteger)addressID
{
    UIAlertView* alterView = [[UIAlertView alloc] initWithTitle:nil message:@"您确定要删除这个地址？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alterView show];
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    //NSLog(@"buttonIndex:%d",buttonIndex);
    if (buttonIndex==0) {
        //取消
    }else if(buttonIndex==1){
        //确定
        [self doactiondelete];
    }
    [alertView setHidden:YES];
}
-(void)doactiondelete
{
    
}
-(void)addressedit:(NSInteger)addressID
{
//    NSLog(@"addressID:%d",addressID);
//    NSLog(@"len:%d",self.dataMArr.count);
    SQNewAddressViewController* navc = [[SQNewAddressViewController alloc]init];
    addr_t item;
    for (NSInteger i=0; i<self.dataMArr.count; i++) {
        //NSLog(@"i:%d",i);
        [[self.dataMArr objectAtIndex:i]getValue:&item];
        NSLog(@"item.address_id:%d",item.address_id);
        if (item.address_id == addressID) {
            navc.showaddress = YES;
            navc.initaddress = item;
            [self.navigationController pushViewController:navc animated:YES];
            break;
        }
    }
}
//读取数据
-(void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
    NSLog(@"get %ld",tag);
    if (tag == 1) {
        if (self.socketLength == 0) {
            ack_my_stuff_t baseInfo;
            [data getBytes:&baseInfo length:sizeof(baseInfo)];
            if (baseInfo.base.error != ACS_SUCCESS) {
                [self.HUD showAnimated:YES whileExecutingBlock:^{
                    [self.HUD show:NO];
                } completionBlock:^{
                    [self initlist];
                }];
                return;
            }
            self.templength =  data.length;
            self.socketLength = baseInfo.base.len;
        }
        else{
            self.templength += data.length;
        }
        if (self.socketTempData == nil) {
            self.socketTempData = [NSMutableData dataWithData:data];
        }else{
            [self.socketTempData appendData:data];
        }
        if (self.templength < self.socketLength) {
            [asyncSocket readDataWithTimeout:-1 tag:self.socketTag];
            return;
        }else{
            ack_my_stuff_t baseInfo;
            [self.socketTempData getBytes:&baseInfo length:sizeof(baseInfo)];
            addr_t address;
            self.dataMArr = nil;
            self.dataMArr = [NSMutableArray array];
            for (int i =0; i< baseInfo.count; i++) {
                [self.socketTempData getBytes:&address range:NSMakeRange(self.socketTempData.length - (baseInfo.count - i)*sizeof(addr_t) - 8,sizeof(address))];
                [self.dataMArr addObject:[NSValue value:&address withObjCType:@encode(struct addr_t)]];
            }
            [self.HUD showAnimated:YES whileExecutingBlock:^{
                [self.HUD show:NO];
            } completionBlock:^{
                [self initlist];
                self.socketTempData = nil;
                self.socketLength = 0;
                self.templength = 0;
            }];
        }
    }
}
@end
